package com.zqr.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 生产者
 */
@Slf4j
public class ThreadProduct implements Runnable{
    private List<String> container;
    private Integer limit; //容器最大容量
    private long million; //睡眠时间

    public ThreadProduct(List<String> container, Integer limit, long million) {
        this.container = container;
        this.limit = limit;
        this.million = million;
    }

    public void product(){
        int i = 0;
       while(true){
           if (container.size() >= limit){
               //停止生产
               try {
                   synchronized (container){
                       log.info("容器内的产品超过上限，停止生产，{} thread waiting ...", Thread.currentThread().getName());
                       container.wait();
                   }
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }

           try {
               Thread.sleep(million);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           container.add("新加的产品数据" + (i++));
           log.info("生产者生产了一个数据,当前 container current size:{}", container.size());
           synchronized (container){
               log.info("生产者唤醒消费者，{} thread use notifyAll ..", Thread.currentThread().getName());
               container.notifyAll();
           }
       }
    }

    @Override
    public void run() {
        product();
    }
}
